<%@ page import="com.engine.jz.util.KsUtils" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="java.lang.reflect.Type" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.google.gson.reflect.TypeToken" %>
<%@ page import="java.util.Objects" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.security.MessageDigest" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%@ page import="cn.hutool.http.HttpRequest" %>
<%@ page import="cn.hutool.http.Header" %>
<%@ page import="java.time.LocalDate" %><%
    String typeA = request.getParameter("type");
    String ryId = request.getParameter("ry");
    String sbIp = request.getParameter("ip");
    String ygxm = request.getParameter("ygxm");
    String ksrq = request.getParameter("ksrq");
    String jsrq = request.getParameter("jsrq");
    out.println("Ks sync start:" + typeA + "<br>");
    out.newLine();
    try {
        KsUtils ksUtils = new KsUtils();
        String paramStr = ksUtils.loginChallenge("admin", sbIp);

        out.println("Ks paramStr:" + paramStr + "<br>");

        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> map = gson.fromJson(paramStr, type);
        out.println("Ks map:" + JSONObject.toJSONString(map) + "<br>");

        Object session_id = map.get("session_id");
        Object challenge = map.get("challenge");
        Object salt = map.get("salt");
        if (Objects.isNull(session_id) || Objects.isNull(challenge) || Objects.isNull(salt)) {
            return;
        }

        // 设备登陆
//        String loginRes = ksUtils.login(session_id.toString(), challengeStr, saltStr);

        String pwd = "jz123456";
        // 获取SHA-256 MessageDigest实例
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        // 将输入字符串转换为字节数组，并更新到digest中
        // 注意：这里简单地将字符串拼接起来，但在实际应用中可能需要更复杂的组合方式
        String input = pwd + salt + challenge;
        digest.update(input.getBytes(StandardCharsets.UTF_8));

        // 计算哈希值
        byte[] hash = digest.digest();

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        out.println("hexString:" + hexString + "<br>");

        Map<String, Object> paramMapA = new HashMap<>();
        paramMapA.put("session_id", session_id);
        paramMapA.put("username", "admin");
        paramMapA.put("password", hexString);
        String url = "http://" + sbIp + "/api/auth/login?type=other";
        String loginRes = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(JSONObject.toJSONString(paramMapA))
                .timeout(20000)
                .execute().body();

        out.println("loginRes:" + loginRes + "<br>");

        Map<String, Object> mapIn = gson.fromJson(loginRes, type);
        out.println("mapIn:" + mapIn + "<br>");
        Object sessionIdNew = mapIn.get("session_id");

        // 条件查询人员信息
        if (StringUtils.equals(typeA, "0")) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("limit", 10);
            paramMap.put("offset", 0);
            paramMap.put("sort", "asc");
            String s = ksUtils.queryHrm(sessionIdNew.toString(), paramMap, sbIp);
            out.println("queryHrm res:" + s + "<br>");
        }
        // 条件查询通行记录
        if (StringUtils.equals(typeA, "1")) {
            // 获取前一天的日期
//            LocalDate currentDate = LocalDate.now();
//            LocalDate previousDate = currentDate.minusDays(1);
//            java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            String formattedDate = previousDate.format(formatter);
//            String startTime = formattedDate + "T00:00:01+08:00";
//            String endTime = formattedDate + "T23:59:59+08:00";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("limit", 1000);
            paramMap.put("offset", 0);
            paramMap.put("sort", "asc");
            paramMap.put("begin_time", ksrq + "T00:00:01+08:00");
            paramMap.put("end_time", jsrq + "T23:59:59+08:00");
            paramMap.put("query_string", ygxm);
            String s = ksUtils.queryMj(sessionIdNew.toString(), paramMap, sbIp);
            out.println("queryMj res:" + s + "<br>");
        }

        // 条件查询人员组信息
        if (StringUtils.equals(typeA, "2")) {

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("limit", 10);
            paramMap.put("offset", 0);
            paramMap.put("sort", "asc");
            String urlT = "http://192.168.0.107/api/groups/query";
            String result = HttpRequest.post(urlT)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();

            out.println("query groups res:" + result + "<br>");
        }

        // 条件查询人员信息
        if (StringUtils.equals(typeA, "3")) {
            String result = HttpRequest.get("http://" + sbIp + "/api/persons/item/" + ryId)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .timeout(20000)
                    .execute().body();
            out.println("queryHrm res:" + result + "<br>");
        }

        // 查询设备上所有人员信息
        if (StringUtils.equals(typeA, "4")) {
            String resultStr = HttpRequest.get("http://" + sbIp + "/api/auth/users")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .timeout(20000)
                    .execute().body();
            out.println("queryHrm res:" + resultStr + "<br>");
        }

        // 查询旷视设备上所有人员信息
        if (StringUtils.equals(typeA, "5")) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("limit", 100);
            paramMap.put("offset", 0);
            paramMap.put("sort", "asc");
            String resultStr = HttpRequest.get("http://" + sbIp + "/api/persons/query")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            out.println("queryHrm res:" + resultStr + "<br>");
        }

        // 查询旷视设备上所有人员信息
        if (StringUtils.equals(typeA, "6")) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("limit", 100);
            paramMap.put("offset", 0);
            paramMap.put("sort", "asc");
            if (StringUtils.isNotEmpty(ygxm)) {
                paramMap.put("query_string", ygxm);
            }
            String resultStr = HttpRequest.get("http://" + sbIp + "/api/persons/query")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.COOKIE, "sessionID=" + session_id)
                    .body(JSONObject.toJSONString(paramMap))
                    .timeout(20000)
                    .execute().body();
            out.println("queryHrm res:" + resultStr + "<br>");
        }

        out.println("sessionIdNew:" + sessionIdNew + "<br>");
        String logoutRes = ksUtils.logout(sessionIdNew.toString(), "192.168.0.107");
        out.println("logoutRes:" + logoutRes + "<br>");
    } catch (Exception e) {
        out.println("error:" + e);
    }
%>